from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtQuick import QQuickView
from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
from PyQt5.QtCore import QThread,QTimer,QUrl
 
import os, sys
import rospy

class QNode(QThread): 

    sumResult = pyqtSignal(int, arguments=['sum'])
    subResult = pyqtSignal(int, arguments=['sub'])
    quitResult = pyqtSignal (name="cmd" )
    sendMsg = pyqtSignal (name="send" )
    sendMsgStr = pyqtSignal (str,name="send" )

    def __init__(self):
        QObject.__init__(self)

        rospy.init_node ( 'qnode' , anonymous=True)

        rospy.on_shutdown(self.ros_hook)

        # rospy.Subscriber ( '/gnss_info' , GnssInfo , self.gnss_info_callback,queue_size=2)
        # self.config_cmd_pub = rospy.Publisher ( '/config_cmd' , ConfigCmd , queue_size=1)

        self.timer = QTimer()
        self.timer.timeout.connect(self.qtimer_callback)
        self.timer.setInterval(1000)
        self.timer.start()

    def run(self):
        rospy.spin()
        # self.quitResult.emit("quit")
        self.quitResult.emit()

    def stop(self):
        rospy.signal_shutdown('stop')

    def ros_hook(self):
        rospy.loginfo("ros shutdown !!") 

    def qtimer_callback(self):
        self.sendMsg.emit()
        self.sendMsgStr.emit("hello yankai!")
        pass
        #self.cmd_info_trigger.emit(self.__cmd_info.copy())

    @pyqtSlot(int, int)
    def sum(self, arg1, arg2):
        self.sumResult.emit(arg1 + arg2)
 
    @pyqtSlot(int, int)
    def sub(self, arg1, arg2):
        self.subResult.emit(arg1 - arg2)
 
def main(): 

    app = QGuiApplication(sys.argv)
    qnode = QNode()
    qnode.start()
    qnode.quitResult.connect(app.quit) 

    engine = QQmlApplicationEngine() # Create QML engine
    engine.rootContext().setContextProperty("qnode", qnode) # And register it in the context of QML self.qnode.trigger.connect(self.update_ui_data)
    
    ''' 
    Load the qml file into the engine 
    '''
    ui_dir = rospy.get_param('~ui_path', 'ui')
    ui_file = os.path.join(ui_dir, 'main.qml')
    rospy.loginfo("ui_file: %s" % ui_file)
    engine.load(ui_file)


    root = engine.rootObjects()[0]
    qnode.sendMsg.connect(root.test_print) 
    qnode.sendMsgStr.connect(root.test_print_msg) 
 
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()